package com.efounder.agency.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.GridLayout.Spec;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.adapter.MatrixTableAdapter;
import com.efounder.adapter.SampleTableAdapter;
import com.efounder.agency.activity.TaskDetaiSecondActivity;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.ospmobilelib.R;
import com.efounder.util.DownAttachGKUtil;
import com.inqbarna.tablefixheaders.TableFixHeaders;

import java.util.ArrayList;
import java.util.List;

public class TableGenerator {
    private static final int MIN_ROW_HEIGHT = 50;
    private static final int TEXT_SIZE_PLAIN = 16;
    private Context context;
    private DisplayMetrics displayMetrics;
//	private int tag = -1;// 标记属于第几列

    // private int oneTextWidth;
    private int oneTextHeight;

    private float actionDownX = -1;
    private float actionDownY = -1;
    private String mcookie;
    private String systemType = "";//oa 费用报销

    public TableGenerator(Context context, String cookie) {
        super();
        this.context = context;
        this.mcookie = cookie;
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

        // 1 获取一个字的宽度
        TextView plainTextView = new TextView(context);
        plainTextView.setTextSize(TEXT_SIZE_PLAIN);
        Paint paint = plainTextView.getPaint();
        Rect rect = new Rect();
        // 返回包围整个字符串的最小的一个Rect区域
        paint.getTextBounds("序", 0, 1, rect);
        // oneTextWidth = rect.width();
        oneTextHeight = rect.height();
    }

    public TableGenerator(Context context, String cookie, String systemType) {
        super();
        this.context = context;
        this.mcookie = cookie;
        this.systemType = systemType;
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

        // 1 获取一个字的宽度
        TextView plainTextView = new TextView(context);
        plainTextView.setTextSize(TEXT_SIZE_PLAIN);
        Paint paint = plainTextView.getPaint();
        Rect rect = new Rect();
        // 返回包围整个字符串的最小的一个Rect区域
        paint.getTextBounds("序", 0, 1, rect);
        // oneTextWidth = rect.width();
        oneTextHeight = rect.height();
    }

    @SuppressLint("ClickableViewAccessibility")
    public ViewGroup generateTable(EFRowSet tableRowSet, int layoutWidthPX) {
        ViewGroup viewGroup = null;
        // TaskDataParser.recurPrint(tableRowSet.getDataSet());
        int columnCount = tableRowSet.getInt("columns", 0);
        Log.i("", "-------columnCount-------" + columnCount);
        if (columnCount == 0) {
            return new LinearLayout(context);
        } else if (columnCount == 1 || columnCount == 2) {// 生成 GridLayout
            List<List<EFRowSet>> tableData = parseData(tableRowSet);
            viewGroup = generateGrid(tableData, layoutWidthPX, columnCount);
            printData(tableData);
        } else if (columnCount == 3) {// 生成 GridLayout
            List<List<EFRowSet>> tableData = parseData(tableRowSet);
            viewGroup = generateGrid3(tableData, layoutWidthPX, columnCount);
            printData(tableData);
        } else {
            /**
             * 生成表格
             */
            // TODO
            List<List<EFRowSet>> tableData = parseData(tableRowSet);
            EFRowSet[][] tableDataArray = new EFRowSet[tableData.size()][tableData
                    .get(0).size()];
            for (int i = 0; i < tableData.size(); i++) {
                List<EFRowSet> rowSets = tableData.get(i);
                for (int j = 0; j < rowSets.size(); j++) {
                    tableDataArray[i][j] = rowSets.get(j);
                }
            }

            //
            // String[][] form = new String[tableData.size()][columnCount];
            // String title = " ";
            // String value = null;
            // for (int a = 0; a < tableData.size(); a++) {
            // List<EFRowSet> tdList = tableData.get(a);
            // // for (List<EFRowSet> tdList : tableData) {
            // System.out.println(tdList.size());
            // for (int i = 0; i < tdList.size(); i++) {
            // // 拿到RowSet
            // EFRowSet tdRowSet = tdList.get(i);
            //
            // String elementName = tdRowSet.getString("elementname", "");
            // if ("input".equals(elementName)) {
            // title = tdRowSet.getString("title", null);
            // value = tdRowSet.getString("value", null);
            // System.out.println("title"+title);
            // }
            // String content = tdRowSet.getString("elementtext", null);
            // if (a == 0) {
            // form[a][i] = content;
            // }
            // if (a == 1) {
            // if (title != null && !title.equals(" ")) {
            // form[a][0] = title;
            // if (i > 0) {
            // form[a][i] = content;
            // }
            // }else {
            // form[a][i] = content;
            // }
            //
            //
            // }
            //
            // System.out.println(content);
            //
            // }
            // }
            // System.out.println("-----------------------");
            // for (int i = 0; i < 2; i++) {
            // for (int j = 0; j < form.length; j++) {
            // System.out.println(form[i][j]);
            // }
            // }
            // System.out.println("-----------------------");
            // 生成表格
            TableFixHeaders tableFixHeaders = new TableFixHeaders(context);

            MatrixTableAdapter<EFRowSet> matrixTableAdapter = new MatrixTableAdapter<EFRowSet>(
                    context, tableDataArray);
            tableFixHeaders.setAdapter(matrixTableAdapter);
            viewGroup = new LinearLayout(context);
            // TextView textView = new TextView(context);
            // textView.setText("列数大于两行的情况。。。");
            viewGroup.addView(tableFixHeaders);
            //横向滑动的table和scrollView冲突问题
            tableFixHeaders.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            actionDownX = event.getX();
                            actionDownY = event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            if (actionDownX != -1) {
                                float xOffet = Math.abs(event.getX() - actionDownX);
                                Log.i("", "tableFixHeaders-----onTouch-xOffet:" + xOffet + ",x轴坐标：" + event.getX() + "," + actionDownX);
                                float yOffet = Math.abs(event.getY() - actionDownY);
                                Log.i("", "tableFixHeaders-----onTouch-:yOffet" + yOffet + ",y轴坐标：" + event.getY() + "," + actionDownY);
                                if (xOffet > yOffet) {
                                    Log.i("", "tableFixHeaders-----onTouch-:requestDisallowInterceptTouchEvent:true");
                                    recurFindScrollView(v, true);
                                    actionDownX = -1;
                                }
//							actionDownX = -1;
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            recurFindScrollView(v, false);
                            v.performClick();
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }

        return viewGroup;
    }

    private void recurFindScrollView(View v, boolean isDisallowInterceptTouchEvent) {
        View parentView = (View) v.getParent();
        if (parentView instanceof ScrollView) {
            ((ScrollView) parentView).requestDisallowInterceptTouchEvent(isDisallowInterceptTouchEvent);
        } else {
            recurFindScrollView(parentView, isDisallowInterceptTouchEvent);
        }

    }

    @SuppressWarnings("unchecked")
    private List<List<EFRowSet>> parseData(EFRowSet tableRowSet) {
        List<List<EFRowSet>> trList = new ArrayList<List<EFRowSet>>();
        if (tableRowSet == null || tableRowSet.getChildDataSet() == null || tableRowSet.getChildDataSet()
                .getRowSetArray() == null) {
            return trList;
        }
        List<EFRowSet> trRowSets = tableRowSet.getChildDataSet()
                .getRowSetArray();
        for (EFRowSet trRowSet : trRowSets) {// tr
            List<EFRowSet> tdRowSets = trRowSet.getChildDataSet()
                    .getRowSetArray();
            List<EFRowSet> tdList = new ArrayList<EFRowSet>();
            trList.add(tdList);
            for (EFRowSet tdRowSet : tdRowSets) {// td
                tdList.add((EFRowSet) tdRowSet.getChildDataSet()
                        .getRowSetArray().get(0));
            }
        }

        return trList;
    }

    private void printData(List<List<EFRowSet>> tableData) {
        for (List<EFRowSet> trList : tableData) {
            for (EFRowSet tdRowSet : trList) {
                Log.i("", "-----" + tdRowSet.getAttriMap());
            }
        }
    }

    /**
     * 生成网格
     *
     * @param
     * @return
     */
    private GridLayout generateGrid(List<List<EFRowSet>> trList,
                                    int layoutWidthPX, int columnCount) {
        GridLayout gridLayout = new GridLayout(context);
        gridLayout.setOrientation(GridLayout.HORIZONTAL);
        gridLayout.setBackgroundColor(Color.GRAY);
        // gridLayout.setBackgroundColor(Color.WHITE);
        gridLayout.setPadding(0, 0, 1, 1);

        gridLayout.setColumnCount(columnCount);
        // 列宽 list
        List<Integer> columnWidths = computeColumnWidths(columnCount,
                layoutWidthPX);

        for (List<EFRowSet> tdList : trList) {
            // 行高
            //XXX yqs
            if (tdList.size() < columnWidths.size()) {
                continue;
            }
            int rowHeight = computeRowHeight(tdList, columnWidths);
            for (int i = 0; i < tdList.size(); i++) {
                //XXX yqs
                if (i >= 2) {
                    continue;
                }
                // 拿到RowSet
                EFRowSet tdRowSet = tdList.get(i);
                // String text = getTdText(tdRowSet);
                if (rowHeight == 0) {// 合并列
                    int columnWidth = layoutWidthPX;
                    rowHeight = (int) (10 * displayMetrics.density);
                    View cell = getTableCell(1, columnCount, columnWidth,
                            rowHeight, tdRowSet);
                    cell.setBackgroundResource(android.R.color.white);
                    gridLayout.addView(cell);
                    break;
                } else {
                    int columnWidth = columnWidths.get(i);
                    View cell = getTableCell(1, 1, columnWidth, rowHeight,
                            tdRowSet);
                    if (i == 0) {// 设置第一列的背景色
                        cell.setBackgroundColor(context.getResources()
                                .getColor(R.color.billdetail_form1));
                    } else if (i == 1) {// 设置第二列的背景色
                        cell.setBackgroundColor(context.getResources()
                                .getColor(R.color.billdetail_form2));
                    }
                    gridLayout.addView(cell);

                }
            }
        }

        return gridLayout;

    }

    /**
     * 生成网格
     *
     * @param
     * @return
     */
    private GridLayout generateGrid3(List<List<EFRowSet>> trList,
                                     int layoutWidthPX, int columnCount) {
        GridLayout gridLayout = new GridLayout(context);
        gridLayout.setOrientation(GridLayout.HORIZONTAL);
        gridLayout.setBackgroundColor(Color.GRAY);
        // gridLayout.setBackgroundColor(Color.WHITE);
        gridLayout.setPadding(0, 0, 1, 1);

        gridLayout.setColumnCount(columnCount);
        // 列宽 list
        List<Integer> columnWidths = computeColumnWidths(columnCount,
                layoutWidthPX);

        for (List<EFRowSet> tdList : trList) {
            // 行高
            //XXX yqs
            if (tdList.size() < columnWidths.size()) {
                continue;
            }
            int rowHeight = computeRowHeight(tdList, columnWidths);
            for (int i = 0; i < tdList.size(); i++) {
                //XXX yqs
                if (i > 2) {
                    continue;
                }
                // 拿到RowSet
                EFRowSet tdRowSet = tdList.get(i);
                // String text = getTdText(tdRowSet);
                if (rowHeight == 0) {// 合并列
                    int columnWidth = layoutWidthPX;
                    rowHeight = (int) (10 * displayMetrics.density);
                    View cell = getTableCell(1, columnCount, columnWidth,
                            rowHeight, tdRowSet);
                    cell.setBackgroundResource(android.R.color.white);
                    gridLayout.addView(cell);
                    break;
                } else {
                    int columnWidth = columnWidths.get(i);
                    View cell = getTableCell(1, 1, columnWidth, rowHeight,
                            tdRowSet);
                    if (i == 0) {// 设置第一列的背景色
                        cell.setBackgroundColor(context.getResources()
                                .getColor(R.color.billdetail_form1));
                    } else if (i == 1) {// 设置第二列的背景色
                        cell.setBackgroundColor(context.getResources()
                                .getColor(R.color.billdetail_form2));
                    } else if (i == 2) {// 设置第3列的背景色
                        cell.setBackgroundColor(context.getResources()
                                .getColor(R.color.billdetail_form2));
                    }
                    gridLayout.addView(cell);

                }
            }
        }

        return gridLayout;

    }

    private View getTableCell(int rowSpan, int colSpan, int width, int height,
                              final EFRowSet tdRowSet) {
        View cellView = null;
        String cellText = getTdText(tdRowSet);
        // 行设置，第一个为参数为第几行，默认可不设置，第二个参数为跨行数，没有则表示不跨行
        Spec rowsSpec = GridLayout.spec(GridLayout.UNDEFINED, rowSpan);
        // 列设置，第一个为参数为第几列，默认可不设置，第二个参数为跨列数，没有则表示不跨行
        Spec colsSpec = GridLayout.spec(GridLayout.UNDEFINED, colSpan);
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowsSpec,
                colsSpec);
        params.width = width;
        params.height = height;
        params.leftMargin = 1;
        params.topMargin = 1;
        params.setGravity(Gravity.FILL);
        // 创建TextView,依据tdRowSet中的数据，给TextView添加其他属性
        TextView textView = new TextView(context);
        //TODO 此属性可以控制文字与边框的距离 2016.9.28  yqs
        textView.setPadding(5, 5, 20, 5);
        textView.setLayoutParams(params);
        textView.setBackgroundColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TEXT_SIZE_PLAIN);
        textView.setText(cellText);
        textView.setTextColor(Color.BLACK);
        String type = tdRowSet.getString("type", null);
        final String url = tdRowSet.getString("value", null);
        // System.out.println("186 type+value:" + type + " " + url);
        // type类型是文件
        if (type != null && type.equals("file") && url != null) {
            String fileType = url.substring(url.lastIndexOf("."));
            /*"doc",@"docx",@"ppt",@"pptx",@"xls",@"xlsx",@"pdf",@"jpg",@"png"*/
            if (fileType.toLowerCase().equals(".doc") || fileType.toLowerCase().equals(".docx") || fileType.toLowerCase().equals(".ppt") || fileType.toLowerCase().equals(".pptx")
                    || fileType.toLowerCase().equals(".xls") || fileType.toLowerCase().equals(".xlsx") || fileType.toLowerCase().equals(".pdf")
                    || fileType.toLowerCase().equals(".jpg") || fileType.toLowerCase().equals(".png")) {

                textView.setTextColor(Color.BLUE);
                textView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if ("FFS".equals(systemType)) {//费用报销
                            DownAttachGKUtil downAttachUtil = new DownAttachGKUtil(context,
                                    url, mcookie, systemType);
                            downAttachUtil.taskStart();
                        } else if ("GKOA".equals(systemType)) { //国勘oa附件下载
                            DownAttachGKUtil downAttachUtil = new DownAttachGKUtil(context,
                                    url, mcookie, systemType);
                            downAttachUtil.taskStart();
                        } else {
                            DownAttachGKUtil downAttachUtil = new DownAttachGKUtil(context,
                                    url, mcookie);
                            downAttachUtil.taskStart();
                        }


                    }
                });
            }
        }
        // type类型是form 合同的签约依据
        if (type != null && type.equals("form")) {
            textView.setTextColor(Color.BLUE);
            textView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String value = tdRowSet.getString("value", "");
                    System.out.println("value:" + value);
                    Intent intent = new Intent(context,
                            TaskDetaiSecondActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("value", value);
                    bundle.putString("type", "form");
                    intent.putExtra("dataSource", bundle);
                    context.startActivity(intent);

                }
            });
        }
        // type类型是html
        if (type != null && type.equals("html")) {
            textView.setTextColor(Color.BLUE);
            textView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String value = tdRowSet.getString("value", "");
                    System.out.println("value:" + value);
                    Intent intent = new Intent(context,
                            TaskDetaiSecondActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("value", value);
                    bundle.putString("type", "html");
                    intent.putExtra("dataSource", bundle);
                    context.startActivity(intent);

                }
            });
        }

        System.out.println("colSpan" + colSpan);
        // if (tag == 0) {
        // textView.setBackgroundColor(context.getResources().getColor(
        // R.color.billdetail_form1));
        // } else if (tag == 1) {
        // textView.setBackgroundColor(context.getResources().getColor(
        // R.color.billdetail_form2));
        // }
        cellView = textView;
        return cellView;
    }

    private static List<Integer> computeColumnWidths(int columnCount,
                                                     int layoutWidthPX) {
        List<Integer> columnWidths = new ArrayList<Integer>();
        if (columnCount == 1) {// 1列的情况
            columnWidths.add(layoutWidthPX);
        } else if (columnCount == 2) {// 2列的情况
            int columnWidth1 = layoutWidthPX / 3;
            int columnWidth2 = layoutWidthPX / 3 * 2;
            columnWidths.add(columnWidth1);
            columnWidths.add(columnWidth2);
        } else if (columnCount == 3) {// 3列的情况
            int columnWidth1 = layoutWidthPX / 7 * 2;
            int columnWidth2 = layoutWidthPX / 7 * 2;
            int columnWidth3 = layoutWidthPX / 7 * 3;
            columnWidths.add(columnWidth1);
            columnWidths.add(columnWidth2);
            columnWidths.add(columnWidth3);
        } else {
            int columnWidth1 = layoutWidthPX / 3;
            int columnWidth2 = layoutWidthPX / 3 * 2;
            int columnWidth3 = 0;
            columnWidths.add(columnWidth1);
            columnWidths.add(columnWidth2);
            columnWidths.add(columnWidth3);
        }

        return columnWidths;
    }

    /**
     * 根据文字多少和列宽，计算列高
     *
     * @param
     * @param columnWidths
     * @return
     */
    private int computeRowHeight(List<EFRowSet> tdRowSets,
                                 List<Integer> columnWidths) {
        int maxRowHeight = 0;
        int oneRowHeight = oneTextHeight * 2;// (int)(ONE_ROW_HEIGHT_PX *
        // displayMetrics.density);
        boolean isTextNull = true;
        for (int i = 0; i < columnWidths.size(); i++) {
            int columnWidth = columnWidths.get(i);
            EFRowSet tdRowSet = tdRowSets.get(i);

            // 判断是否一行所有列文字都为null
            String text = getTdText(tdRowSet);
            if (text != null && !"".equals(text)) {
                isTextNull = false;
            }
//			else {
//				text ="   "
//				isTextNull = false;
//			}

            // 测量文字宽度
            TextView plainTextView = new TextView(context);

            plainTextView.setTextSize(TEXT_SIZE_PLAIN);
            Paint paint = plainTextView.getPaint();
            float textWidth = paint.measureText(text) + 6;
            int rowCount = (int) Math.ceil(textWidth / columnWidth);
            //计算换行符个数
            if (text.contains("\n")) {
                int countN = countStr(text, "\n", 0);
                Log.i("", "=================包换换行符个数================" + countN);
                rowCount = rowCount + countN / 2;
            }
            int rowHeight = rowCount * oneRowHeight;
            if (rowHeight > maxRowHeight) {
                maxRowHeight = rowHeight;
            }
        }
        if (isTextNull) {
            maxRowHeight = 0;// 如果，一行所有列文字都为null 返回高度 0
        } else if (maxRowHeight < MIN_ROW_HEIGHT) {
            maxRowHeight = (int) (MIN_ROW_HEIGHT * displayMetrics.density);
        } else {
            maxRowHeight = maxRowHeight + (int) (10 * displayMetrics.density)
                    * 2;
        }

        return maxRowHeight;
    }

    /**
     * 判断str1中包含str2的个数
     *
     * @param str1
     * @param str2
     * @return counter
     */
    public static int countStr(String str1, String str2, int counter) {
        if (str1.indexOf(str2) == -1) {
            return counter;
        } else if (str1.indexOf(str2) != -1) {
            counter++;
            counter = countStr(str1.substring(str1.indexOf(str2) + str2.length()), str2,
                    counter);
            return counter;
        }
        return counter;
    }

    /**
     * 获取一个网格的文本
     *
     * @param tdRowSet
     * @return
     */
    private String getTdText(EFRowSet tdRowSet) {
        String text = null;

        String elementName = tdRowSet.getString(TaskDataParser.KEY_ELEMENTNAME,
                "");

        if ("input".equals(elementName)) {
            text = tdRowSet.getString("title", "");

        } else {
            text = tdRowSet.getString(TaskDataParser.KEY_ELEMENTTEXT, "");
        }
        text = text.replace("CN=", "").replace("/O=sipc", "").replace("/sipc", "");
        return text;
    }

    public class MyAdapter extends SampleTableAdapter {

        private final int width;
        private final int height;

        public MyAdapter(Context context) {
            super(context);

            Resources resources = context.getResources();

            width = resources.getDimensionPixelSize(R.dimen.table_width);
            height = resources.getDimensionPixelSize(R.dimen.table_height);
        }

        @Override
        public int getRowCount() {
            return 20;
        }

        @Override
        public int getColumnCount() {
            return 6;
        }

        @Override
        public int getWidth(int column) {
            return width;
        }

        @Override
        public int getHeight(int row) {
            return height;
        }

        @Override
        public String getCellString(int row, int column) {
            return "Lorem (" + row + ", " + column + ")";
        }

        @Override
        public int getLayoutResource(int row, int column) {
            final int layoutResource;
            switch (getItemViewType(row, column)) {
                case 0:
                    layoutResource = R.layout.item_table1_header;
                    break;
                case 1:
                    layoutResource = R.layout.item_table1;
                    break;
                default:
                    throw new RuntimeException("wtf?");
            }
            return layoutResource;
        }

        @Override
        public int getItemViewType(int row, int column) {
            if (row < 0) {
                return 0;
            } else {
                return 1;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }
    }
}
